package com.qk.management.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qk.common.PageResult;
import com.qk.common.enums.ParamEnum;
import com.qk.common.exception.CommonException;
import com.qk.dto.activity.ActivityDTO;
import com.qk.entity.Activity;
import com.qk.management.mapper.ActivityMapper;
import com.qk.management.service.ActivityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

@Service
@SuppressWarnings("all")
public class ActivityServiceImpl implements ActivityService {
    @Autowired
    ActivityMapper activityMapper;

    @Override
    public PageResult<Activity> listActivities(ActivityDTO activityDto) {
        PageHelper.startPage(activityDto.getPage(), activityDto.getPageSize());
        List<Activity> list = activityMapper.selectByPage(activityDto);
        Page<Activity> page = (Page<Activity>) list;
        return PageResult.<Activity>builder()
                .total(page.getTotal())
                .rows(page.getResult())
                .build();
    }

    @Override
    public void addActivity(Activity activity) {
        boolean hasNull = BeanUtil.hasNullField(activity,"id","voucher","discount","updateTime","createTime");
        if(hasNull){
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        activity.setCreateTime(LocalDateTime.now());
        activity.setUpdateTime(LocalDateTime.now());
        activityMapper.insert(activity);
    }

    @Override
    public void deleteActivity(Integer id) {
        if(Objects.isNull( id)){
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        activityMapper.deleteById(id);
    }

    @Override
    public void updateActivity(Activity activity) {
        activity.setUpdateTime(LocalDateTime.now());
        activityMapper.update(activity);
    }

    @Override
    public Activity getById(Integer id) {
        if(Objects.isNull( id)){
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        return activityMapper.getById(id);
    }

    @Override
    public List<Activity> getByType(Integer type) {
        if(Objects.isNull( type)){
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        List<Activity> list = activityMapper.getByType(type);
        return list;
    }
}
